package com.systemsjr.mpf.account;

import com.systemsjr.mpf.R;
import com.systemsjr.mpf.expense.Expense;
import com.systemsjr.mpf.expense.ExpenseType;

import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class ViewInstanceExpenseByType extends ListActivity {

	private SimpleCursorAdapter adapter;
	private ListView listView;
	private Cursor c;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_instance_expense_by_type);

		AccountInstance instance = null;
		ExpenseType type = null;
		Bundle bundle = getIntent().getExtras();

		/**
		 * The Master of the screen
		 */
		if (bundle != null && bundle.size() > 0) {

			if (bundle.get(AccountInstance.TABLE_NAME) != null) {
				instance = (AccountInstance) bundle
						.get(AccountInstance.TABLE_NAME);
				TextView instanceText = (TextView) findViewById(R.id.instanceText);
				instanceText.setText(instance.getInstance());

			}

			if (bundle.get(ExpenseType.TABLE_NAME) != null) {

				type = (ExpenseType) bundle.get(ExpenseType.TABLE_NAME);

				TextView typeText = (TextView) findViewById(R.id.typeText);
				typeText.setText(type.getExpenseType());

				TextView spentText = (TextView) findViewById(R.id.spentText);
				spentText.setText("" + type.getSpent());
			}
			String[] from = { Expense.DESCRIPTION, Expense.AMOUNT,
					Expense.EXPENSE_DATE };
			int[] to = { R.id.exp_description, R.id.exp_amount,
					R.id.exp_expense_date };
			String selection = Expense.ACCOUNT_INSTANCE + " = ? AND "
					+ Expense.EXPENSE_TYPE + " = ?";

			if (instance != null && type != null) {
				String[] selectionArgs = { "" + instance.getId(),
						"" + type.getId() };
				c = getContentResolver().query(Expense.CONTENT_URI,
						Expense.PROJECTIONS, selection, selectionArgs,
						"AMOUNT DESC");
				adapter = new SimpleCursorAdapter(this,
						R.layout.expense_list_entry, c, from, to, 0);
				listView = getListView();

				listView.setAdapter(adapter);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.view_instance_expense_by_type, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
